//
//  PhotosViewController.swift
//  photoDemo
//
//  Created by mysj on 16/7/29.
//  Copyright © 2016年 zeng. All rights reserved.
//

import UIKit

import Photos

class PhotosViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        PHCachingImageManager().startCachingImagesForAssets(photos, targetSize: CGSizeMake(100, 300), contentMode: .AspectFill, options: options)
        setup()
        
       
    }
    
    
    func getImage(index: Int, F: (image: UIImage) -> ()) {
        PHImageManager.defaultManager().requestImageForAsset(photos[index], targetSize: phitemSize, contentMode: .AspectFill, options: options,resultHandler: { (result, info) in
            if result != nil {
                let k = "img" + "\(self.indx.row)"
                let newImg = result!.imageCompressForWidth(self.phitemSize.width)
                self.imgChache.setObject(newImg, forKey: k)
                F(image: newImg)
            }
        })
    }
    
    private lazy var pimageView = UIImageView()
    
    private let phitemSize: CGSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width / 3.1, 216 - 44)
    
    private lazy var indx = NSIndexPath()
    
    private lazy var imgChache = NSCache()
    
    private let options: PHImageRequestOptions = {
        let  op = PHImageRequestOptions()
        op.deliveryMode = .HighQualityFormat
//        HighQualityFormat FastFormat
        op.resizeMode = .Exact
        op.synchronous = true
        return op
    }()
    
    private lazy var photos: [PHAsset] = {
        
        var assets = [PHAsset]()
        let _ops = PHFetchOptions()
        _ops.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        PHAsset.fetchAssetsWithOptions(_ops).enumerateObjectsUsingBlock({ (photo, _, _) in assets.append(photo as! PHAsset) })
        return assets
    }()

    private lazy var photoView: UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = self.phitemSize
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 5
        flowLayout.scrollDirection = .Horizontal
        
        let  pView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        pView.showsHorizontalScrollIndicator = false
        //        photoView_.pagingEnabled = true
        pView.backgroundColor = UIColor.whiteColor()
        pView.registerClass(photoCell.classForCoder(), forCellWithReuseIdentifier: "abc")
        return pView
    }()
    
}

 //MARK: UICollectionViewDataSource,UICollectionViewDelegate
extension PhotosViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        indx = indexPath
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("abc", forIndexPath: indexPath) as! photoCell
        
        var image: UIImage?
        let k = "img" + "\(indexPath.row)"
    
        if  ((imgChache.objectForKey(k) as? UIImage) != nil) {
            image = imgChache.objectForKey(k) as? UIImage
        } else {
             getImage(indexPath.row, F: { (img) in
                image = img
            })
        }
        cell.imageView.image = image
        return cell
    }
    
    //UICollectionViewDelegate
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let manager = PHImageManager.defaultManager()
        
        let initialRequestOptions = PHImageRequestOptions()
        initialRequestOptions.synchronous = true
        //Exact 高质量 //Fast  低质量
        initialRequestOptions.resizeMode = .Exact
        //HighQualityFormat //高清  Opportunistic 小巧 FastFormat快速
        initialRequestOptions.deliveryMode = .HighQualityFormat
        
        manager.requestImageForAsset(photos[indexPath.row], targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: initialRequestOptions) { (resut, _) in
            
            self.pimageView.image = resut!.imageCompressForWidth(UIScreen.mainScreen().bounds.width)
        }
//        print(indexPath.row)
    }
}


extension PhotosViewController {
    
    func setup() {
        view.addSubview(photoView)
        view.addSubview(pimageView)
        pimageView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height * 0.5)
        photoView.frame = CGRectMake(5, 300, view.frame.size.width - 10, 300)
        photoView.dataSource = self
        photoView.delegate = self
    }
    
}

class photoCell: UICollectionViewCell {
    
   lazy var imageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView.frame = contentView.bounds
        contentView.addSubview(imageView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension UIImage {

    func imageCompressForWidth(width: CGFloat) -> UIImage {
        var newImage: UIImage!
        let W  = self.size.width
        let H  = self.size.height
        let targetH = self.size.height / (W / width)
        let size = CGSizeMake(width, targetH)
        
        var scaleFactor: CGFloat = 0.0
        var scaledW = width
        var scaledH = targetH
        if  CGSizeEqualToSize(self.size, size) {
            scaleFactor = (width / W > targetH / H) ? width / W: targetH / H
            print(scaleFactor)
            scaledW = W * scaleFactor
            scaledH = H * scaleFactor
        }
        
        UIGraphicsBeginImageContext(size);
        self.drawInRect(CGRectMake(0, 0, scaledW, scaledH))
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext()
        return newImage
    }
}

/**func getAllphotos() -> () {
 
 
 //        // 1. 创建搜索集合// 列出所有相册智能相册
 //        let result = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.AlbumRegular, options: nil)
 
 let allPhotosOptions = PHFetchOptions()
 allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
 
 let opstions =  PHContentEditingInputRequestOptions()
 opstions.canHandleAdjustmentData = {(adjustmentData:PHAdjustmentData ) -> (Bool) in
 return adjustmentData.formatIdentifier == "AdjustmentFormatIdentifier" && adjustmentData.formatVersion == "1.0"
 }
 
 
 let allPhotos = PHAsset.fetchAssetsWithOptions(allPhotosOptions)
 
 allPhotos.enumerateObjectsUsingBlock { (asset, _, _) in
 
 let photo = asset as! PHAsset
 
 photo.requestContentEditingInputWithOptions(opstions, completionHandler: { (contentEditingInput, info) in
 let url = contentEditingInput!.fullSizeImageURL
 let uniformTypeIdentifier = contentEditingInput?.creationDate
 print(uniformTypeIdentifier)
 print(url)
 
 
 //             PHContentEditingInput // 头文件 所有资源
 })
 }
 }
 */


/*          print(info)
 PHImageResultDeliveredImageFormatKey: 9999,
 PHImageFileUTIKey: public.jpeg,
 PHImageResultIsDegradedKey: 0,
 PHImageFileOrientationKey: 0,
 PHImageFileSandboxExtensionTokenKey: 282f0915080376275c88626d46def1d0d0af11cb;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;00000001;01000002;0000000004d16adb;/users/mysj/library/developer/coresimulator/devices/fc05fcc0-50bd-4afa-9b60-16fcc67c8bed/data/media/dcim/100apple/img_0002.jpg,
 PHImageResultOptimizedForSharing: 0,
 PHImageResultIsInCloudKey: 0,
 PHImageResultIsPlaceholderKey: 0,
 PHImageFileURLKey: file: .....100APPLE/IMG_0002.JPG,
 PHImageResultWantedImageFormatKey: 4035]
 */
